package bupt.xixi.learning.beans.factory.support;

import bupt.xixi.learning.ClassUtils;
import bupt.xixi.learning.beans.factory.BeanFactory;
import bupt.xixi.learning.beans.factory.ConfigurableListableBeanFactory;
import bupt.xixi.learning.beans.factory.FactoryBean;

import java.util.ArrayList;
import java.util.List;

import bupt.xixi.learning.beans.BeansException;
import bupt.xixi.learning.beans.factory.config.BeanDefinition;
import bupt.xixi.learning.beans.factory.config.BeanPostProcessor;
import bupt.xixi.learning.beans.factory.config.ConfigurableBeanFactory;

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    private final List<BeanPostProcessor> beanPostProcessor = new ArrayList<>();
    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    @Override
    public Object getBean(String name) throws BeansException{
        return doGetBean(name, null);

    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    protected <T> T doGetBean(String beanName, Object[] args){
        // 缓存中是否有该bean
        Object bean = getSingleton(beanName);
        if (bean != null) {
            // return (T) bean;
            return (T) getObjectForBeanInstance(bean, beanName);
        }
        // 没有则通过反射创建一个
        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        // return (T) createBean(beanName, beanDefinition, args);
        bean = createBean(beanName, beanDefinition, args);
        return (T) getObjectForBeanInstance(bean, beanName);

    }

    private Object getObjectForBeanInstance(Object bean, String beanName) {
        if (!(bean instanceof FactoryBean)) {
            return bean;
        }

        Object object = getCacheObjectForFactoryBean(beanName);
        if (null == object) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) bean;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }
        return object;
    }

    protected abstract BeanDefinition getBeanDefinition(String name);

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessor.remove(beanPostProcessor);
        this.beanPostProcessor.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessor;
    }

    public ClassLoader getBeanClassLoader() {
        return this.beanClassLoader;
    }
}
